<?php

namespace app\index\controller;

use app\BaseController;
use think\facade\Db;
use think\Request;
use think\facade\View;

/*
 * 惠充 2.0
 */
class V2 extends BaseController
{
    /**
     * 初始化[01] agent_service_config 表数据
     *
     * https://jj.dmjvip.com/index/v2/initAgentServiceConfig
     */
    public function initAgentServiceConfig()
    {
        exit;
        $agent = Db::name('agent')
            ->field('id, mobile_discount_slow, mobile_discount_fast')
            ->select()
            ->toArray();
        $insert = [];
        $ids = Db::name('agent_service_config')
            ->where('serv_type', 1)
            ->column('agent_id');
        $num = 0;
        foreach ($agent as $v) {
            if (in_array($v['id'], $ids)) {
                continue;
            }
            $insert[] = [
                'agent_id' => $v['id'],
                'status' => 1,
                'serv_type' => 1,
                'discount_slow' => $v['mobile_discount_slow'],
                'discount_fast' => $v['mobile_discount_fast'],
            ];
            $num += 1;
        }
        if ($insert) {
            Db::name('agent_service_config')
                ->insertAll($insert);
        }
        echo $num;
    }

    /**
     * 初始化[02]
     *
     * 初始化模板引用次数
     */
    public function initTemplateUseNum()
    {
        exit;
        for ($i = 1; $i < 5; $i++) {
            $count = Db::name('agent_channel')
                ->where('template_id', $i)
                ->count();
            if ($count) {
                Db::name('template')
                    ->where('id', $i)
                    ->update([
                        'use_num' => $count,
                    ]);
            }
        }
        echo 'ok';
    }

    /**
     * 淘宝联盟授权
     * @auth true
     */
    public function auth(Request $request)
    {
        $id = input('id');
        $redirect_uri = $request->domain() . '/index/v2/getAccessToken?id=' . $id;
        $url = 'http://tbapi.youqing1688.com:7001/tbapinew/authorize?dmjkey=dmj&redirect_uri=' . urlencode($redirect_uri);
        header('Location: ' . $url);
    }

    /**
     * 淘宝联盟: 获取 access token
     */
    public function getAccessToken(Request $request)
    {
        $id = input('get.id');
        $code = input('get.code');
        if (empty($code) || empty($id)) {
            View::assign('message', '参数有误');
            return View::fetch('auth_failed');
        }
        $redirect_uri = $this->app->request->domain() . '/index/v2/getAccessToken?id=' . $id;
        $url = 'http://tbapi.youqing1688.com:7001/tbapinew/authorize?dmjkey=dmj&redirect_uri=' . urlencode($redirect_uri);
        $data = [
            'grant_type' => 'authorization_code',
            'client_id' => env('taobao.client_id'),
            'client_secret' => env('taobao.client_secret'),
            'code' => $code,
            'redirect_uri' => $url,
            'state' => '1',
            'view' => 'web',
        ];
        $url = 'https://oauth.taobao.com/token';
        $res = curlPost($url, http_build_query($data));
        $res = json_decode($res, true);
        if (!empty($res['access_token'])) {
            $this->app->db->name('alimama')
                ->where('agent_id', $id)
                ->update([
                    'session_key' => $res['access_token'],
                    'auth_expire_time' => time() + $res['expires_in'],
                    'auth_status' => 1,
                ]);
            return View::fetch('auth_success');
        } else {
            View::assign('message', $res['error_description'] ?? '授权失败，请稍后重试或者联系管理员处理');
            return View::fetch('auth_failed');
        }
        /*

        // 授权失败
        {
            "error_description": "authorize code ctFV071qclYplk9MrENj5T8U26484249 invalidate,please authorize again.",
            "error": "invalid_client"
        }

        // 授权成功
        {
            "w1_expires_in": 2592000,
            "refresh_token_valid_time": 1625214927030,
            "taobao_user_nick": "%E6%B5%B7%E7%9B%97%E6%B9%BE04",
            "re_expires_in": 2592000,
            "expire_time": 1625214927030,
            "token_type": "Bearer",
            "access_token": "6201a1504417bce9f0f5632ZZac89a01d0fc1c9d95ba7bf1687161643",
            "taobao_open_uid": "AAFG_IIkAKX2K6S7nDn6GxV4",
            "w1_valid": 1625214927030,
            "refresh_token": "6200f158ece8a4bc170722dfhbc9a87e47cae67ad02ffbe1687161643",
            "w2_expires_in": 300,
            "w2_valid": 1622623227030,
            "r1_expires_in": 2592000,
            "r2_expires_in": 86400,
            "r2_valid": 1622709327030,
            "r1_valid": 1625214927030,
            "taobao_user_id": "1687161643",
            "expires_in": 2592000
        }
        */
    }
}
